var app = require('express')();
var express = require("express");
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(9092);
app.use(express.static("./static"));

//向view页面发送信息
function sendViewMessage(client ,msg){
  for (var k in io.sockets.sockets) {
    //这里的k是client.id的值
    var client = io.sockets.sockets[k];
    if(client.isViewPage){
      client.emit('viewMessage', msg);
    }
  }
}

io.on('connection', function (client) {
  let name = `【${client.id}】`;
  console.log(`${name}新客户端连接`);
  
  // 接收客户端发送消息
  client.on('controlMessage', function(msg) {
   //console.log(`${name}接收到客户端的消息：${msg}`);
   sendViewMessage(client, msg)
  });
  
  //给客户端标记view页面标识
  client.on('setViewName', function(msg) {
   client.isViewPage = msg;
   console.log(`${name}给客户端标记view页面标识`);
  });
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  // 接收客户端关闭连接消息
  client.on('close', function() {
    console.log(`${name}关闭连接`);
  });
  // 断开连接
  client.on('disconnect', function() {
    console.log(`${name}断开连接`);
  })
  // 定义客户端异常处理
  client.on('error', function(err) {
    console.log(`${name}发送异常：`,err);
  })
});